﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Tools.Extensions;

public class JsonHelper
{
  private const string IndentString = "    ";
  public static string LineEnding = "System";

  public static string FormatJson(string str)
  {
    int count = 0;
    bool flag1 = false;
    StringBuilder sb = new StringBuilder();
    for (int index = 0; index < str.Length; ++index)
    {
      char ch = str[index];
      switch (ch)
      {
        case '"':
          sb.Append(ch);
          bool flag2 = false;
          int num = index;
          while (num > 0 && str[--num] == '\\')
            flag2 = !flag2;
          if (!flag2)
          {
            flag1 = !flag1;
            break;
          }
          break;
        case ',':
          sb.Append(ch);
          if (!flag1)
          {
            sb.Append(JsonHelper.GetLineEnding());
            Enumerable.Range(0, count).ForEach<int>((Action<int>) (item => sb.Append("    ")));
            break;
          }
          break;
        case ':':
          sb.Append(ch);
          if (!flag1)
          {
            sb.Append(" ");
            break;
          }
          break;
        case '[':
        case '{':
          sb.Append(ch);
          if (!flag1)
          {
            sb.Append(JsonHelper.GetLineEnding());
            Enumerable.Range(0, ++count).ForEach<int>((Action<int>) (item => sb.Append("    ")));
            break;
          }
          break;
        case ']':
        case '}':
          if (!flag1)
          {
            sb.Append(JsonHelper.GetLineEnding());
            Enumerable.Range(0, --count).ForEach<int>((Action<int>) (item => sb.Append("    ")));
          }
          sb.Append(ch);
          break;
        default:
          sb.Append(ch);
          break;
      }
    }
    return sb.ToString();
  }

  private static string GetLineEnding()
  {
    if (JsonHelper.LineEnding == "LF")
      return "\n";
    return JsonHelper.LineEnding == "CRLF" ? "\r\n" : Environment.NewLine;
  }
  
}
